package com.chuangke.admin.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chuangke.admin.entity.SysRole;
import com.chuangke.admin.entity.SysUser;
import com.chuangke.admin.entity.SysUserRole;
import com.chuangke.admin.service.SysRoleService;
import com.chuangke.admin.service.SysUserRoleQueryService;
import com.chuangke.admin.service.SysUserRoleService;
import com.chuangke.admin.service.SysUserService;

@Service
public class SysUserRoleQueryServiceImpl implements SysUserRoleQueryService {
	
	@Autowired
	private SysRoleService sysRoleService ;
	
	@Autowired
	private SysUserService sysUserService ;
	
	@Autowired
	private SysUserRoleService sysUserRoleService ;

	@Override
	public List<SysUser> findUserByRoleName(String role) {
		SysRole sysRole = sysRoleService.findByName(role) ;
		
		Map<String, List<SysUserRole>> map = sysUserRoleService.findAll();
		List<SysUserRole> allList = new ArrayList<>() ;
		map.values().forEach(allList::addAll);
		List<String> roleList = allList.stream().filter(userRole->sysRole.getId().equals(userRole.getRoleId())).map(SysUserRole::getUserId).collect(Collectors.toList());
		Map<String,SysUser> allUser = sysUserService.findMap() ;
		
		return allUser.values().stream().filter(user->roleList.contains(user.getId())).collect(Collectors.toList());
	}
	
	@Override
	public List<SysRole> findRoleByUserId(String id) {
		List<String> userRoleList = findByUserId(id).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
		return sysRoleService.findList().stream().filter(role->userRoleList.contains(role.getId())).collect(Collectors.toList());
	}
	
	@Override
	public List<SysUserRole> findByUserId(String id) {
		Map<String, List<SysUserRole>> map = sysUserRoleService.findAll();
		List<SysUserRole> roleList =  map.get(id) ;
		if(CollectionUtils.isEmpty(roleList)) {
			return new ArrayList<>() ;
		}
		
		roleList = roleList.stream().filter(userRole->{
			SysRole sysRole = sysRoleService.findById(userRole.getRoleId()) ;
			if(sysRole != null) {
				userRole.setRoleCode(sysRole.getName());
				userRole.setRoleName(sysRole.getRemarks());
				return true ;
			}
			return false ;
		}).collect(Collectors.toList()) ;
		return roleList;
	}

	@Override
	public boolean isUserHaveRoleName(String userId, String roleName) {
		List<SysUserRole> userRoles = findByUserId(userId) ;
		
		for(SysUserRole sur : userRoles) {
			SysRole sysRole = sysRoleService.findById(sur.getRoleId()) ;
			if(roleName.equals(sysRole.getName())) {
				return true ;
			}
		}
		
		return false;
	}

}
